<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 优惠券操作类
 * @package  htdocs
 * @subpackage  module
 * @author   allen.qiang
 * @version 1.0
 */

quanli_require('module/base/selector/gSelectorHandler.class.php');
quanli_require('module/base/selector/custSelector.class.php');
quanli_require('module/base/common/quanliCommon.class.php');

class couponHandler {

    private $dbca = null;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }


    /**
     * 查询优惠券列表
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchCoupon(&$arg_array) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //优惠券名称
        if(isset($arg_array['couponName']) && !empty($arg_array['couponName']) ){
            $sql .= ' AND couponName LIKE ? ';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['couponName']) . '%';
        }

        //开始日期
        if(isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
            $sql .= ' AND startDate >= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
        }

        //结束日期
        if(isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND endDate <= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        //优惠券发放方式
        if(isset($arg_array['couponType']) && in_array($arg_array['couponType'], array(1, 2, 3)) ){
            $sql .= ' AND couponType = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponType'];
        }

        //万能码
        if (isset($arg_array['wncode']) && !empty($arg_array['wncode'])) {
            $sql .= ' AND wncode = ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['wncode'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_coupon ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_coupon ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    if ($item->couponType == 1)
                        $type_name = '编号礼品券';
                    else if ($item->couponType == 2)
                        $type_name = '账户礼品券';
                    else if ($item->couponType == 3)
                        $type_name = '万能码';
                    $item_array[] = array(
                        'couponID' => $item->couponID,            //ID
                        'couponName' => $item->couponName,        //名称
                        'startDate' => $item->startDate,          //开始日期
                        'endDate' => $item->endDate,              //结束日期
                        'couponType' => $item->couponType,        //发放方式
                        'type_name' => $type_name,                //发放方式名称
                        'useFlg' => $item->useFlg,                //使用标志
                        'amount' => $item->amount,                //优惠券金额
                        'limitMoney' => $item->limitMoney,        //订单使用限额
                        'wncode' => $item->wncode,                //万能码
                        'totalNum' => $item->totalNum,            //发放数量
                        'validity' => $item->validity,            //有效期
                        'goodsSelector' => $item->goodsSelectorID,  //商品筛选器
                        'userSelector' => $item->userSelectorID,    //用户筛选器
                        'description' => $item->description,      //描述
                        'useNum' => $item->useNum,                //已使用的数目
                        'isGenerate' => $item->isGenerate,         //是否已生成优惠券
                        'useType' => $item->useType,                //优惠券使用类型
                        'code_number'=>$item->code_number,          //券号长度
                        'departmentID'=>$item->departmentID,
                        'departmentName'=>$item->departmentName
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询优惠券编号信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchCouponCode( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //优惠券编号
        if (isset($arg_array['code']) && !empty($arg_array['code'])) {
            $sql .= ' AND code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['code'];
        }

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //类型
        if (isset($arg_array['couponType']) && in_array($arg_array['couponType'], array(1, 2, 3))) {
            $sql .= ' AND couponType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponType'];
        }

        //订单号
        if (isset($arg_array['billNo']) && !empty($arg_array['billNo'])) {
            $sql .= ' AND billNo = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['billNo'];
        }

        //是否使用
        if (isset($arg_array['used']) && in_array($arg_array['used'], array(1, 2, 3))) {
            if ($arg_array['used'] == 1) {
                $sql .= ' AND billNo IS NULL';
            } else if ($arg_array['used'] == 2) {
                $sql .= ' AND billNo IS NOT NULL';
            } else {
                $sql .= ' AND billNo IS NULL AND endDate < "' . date(G_DEFAULT_DATE_FORMAT) . '"';
            }
        }

        //截止日期
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_coupon_code ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_coupon_code ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $temp_arg_array = array(
                        'couponID' => $item->couponID,
                        'useFlg' => 1
                    );
                    $coupon_array = $this->searchCoupon( $temp_arg_array );
                    if (!$coupon_array) {
                        continue;
                    }

                    $item_array[] = array(
                        'code' => $item->code,
                        'couponName' => $coupon_array[0]['couponName'],
                        'couponID' => $item->couponID,
                        'pcustID' => $item->pcustID,
                        'amount' => $item->amount,
                        'endDate' => $item->endDate,
                        'billNo' => $item->billNo,
                        'useTime' => $item->useTime,
                        'useAmount' => $item->useAmount,
                        'remark' => $item->remark,
                        'createTime' => $item->createTime,
                        'couponType' => $item->couponType,
                        'limitMoney' => $item->limitMoney
                    );
                }
            }

            if (isset($arg_array['code']) && !empty($arg_array['code'])) {
                return $item_array[0];
            } else {
                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 变更使用状态
     * @param int $couponID 优惠券ID
     * @return array
     * @throws Exception
     */
    public function changeCouponStatus( $couponID ) {

        if (!isset($couponID) || !is_numeric($couponID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $coupon_obj = new entity('promotion_coupon');
            $coupon_obj->couponID = $couponID;
            if (!$this->dbca->fetch($coupon_obj)) {
                throw new Exception('优惠券信息没有找到', 404);
            }
            $coupon_obj->useFlg = $coupon_obj->useFlg == 1 ? 0 : 1;
            $this->dbca->save($coupon_obj);

            if ($coupon_obj->useFlg) {
                return array( 'code' => 200, 'message' => '优惠券启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '优惠券禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 新增或修改优惠券信息
     * @param array $arg_array 优惠券数组
     * @return array
     * @throws Exception
     */
    public function editCoupon( $arg_array ) {

        //实例化公共类
        $commHandler = new commHandler();

        if (!isset($arg_array['couponID'], $arg_array['operator']) || !is_numeric($arg_array['couponID']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($arg_array['couponName']) || empty($arg_array['couponName'])) {
            return array( 'code' => 400, 'message' => '优惠券名不能为空' );
        }

        if (!isset($arg_array['startDate'], $arg_array['endDate']) || !$commHandler->isDate($arg_array['startDate']) || !$commHandler->isDate($arg_array['endDate'])) {
            return array( 'code' => 400, 'message' => '优惠券使用日期不能为空' );
        }if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
        }

        if (!isset($arg_array['couponType']) || !in_array($arg_array['couponType'], array(1, 2, 3))) {
            return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
        }

        if (!isset($arg_array['useType']) || !in_array($arg_array['useType'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择优惠券使用方式' );
        }

        if (!isset($arg_array['useType']) || !in_array($arg_array['useType'], array(1, 2))) {
            return array( 'code' => 400, 'message' => '请选择优惠券使用方式' );
        }

        if (!isset($arg_array['limitMoney']) || !$commHandler->isMoney($arg_array['limitMoney']) || $arg_array['limitMoney'] < 0) {
            return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
        }

        if (!isset($arg_array['amount']) || !$commHandler->isMoney($arg_array['amount']) || $arg_array['amount'] <= 0) {
            return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
        }

        if ($arg_array['couponType'] == 1 || $arg_array['couponType'] == 2) {
            if (!isset($arg_array['totalNum']) || !$commHandler->isInteger($arg_array['totalNum'], 1)) {
                return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
            }
            if (!isset($arg_array['code_number']) || !$commHandler->isInteger($arg_array['code_number'], 1)) {
                return array( 'code' => 400, 'message' => '券号长度不能为空且必须是大于0的整数' );
            }

        } else {
            $arg_array['totalNum'] = null;
        }


        if ($arg_array['couponType'] == 2) {

            if (!isset($arg_array['validity']) || !$commHandler->isInteger($arg_array['validity'], 1)) {
                return array( 'code' => 400, 'message' => '有效期不能为空且必须是大于0的整数' );
            }
            $arg_array['wncode'] = null;

        } else if ($arg_array['couponType'] == 3) {

            if (!isset($arg_array['wncode']) || empty($arg_array['wncode'])) {
                return array( 'code' => 400, 'message' => '万能码不能为空' );
            }
            $arg_array['validity'] = 0;

        } else {

            $arg_array['wncode'] = null;
            $arg_array['validity'] = 0;

        }

        if ( !isset($arg_array['goodsSelectorID']) ) {
            $arg_array['goodsSelectorID'] = 0;
        }

        if ( !isset($arg_array['userSelectorID']) ) {
            $arg_array['userSelectorID'] = 0;
        }

        if ( !isset($arg_array['description']) ) {
            $arg_array['description'] = null;
        }

        try {

            //查询优惠券信息并修改或新增优惠券
            $coupon_obj = new entity('promotion_coupon');
            if ($arg_array['couponID'] > 0) {
                $coupon_obj->couponID = $arg_array['couponID'];
                if (!$this->dbca->fetch($coupon_obj)) {
                    throw new Exception('优惠券信息没有找到', 404);
                }
            } else {
                $coupon_obj->creator = $arg_array['operator'];
                $coupon_obj->isGenerate = 0;
                $coupon_obj->useFlg = 1;
            }
            $coupon_obj->couponName = $commHandler->convertVar($arg_array['couponName']);
            $coupon_obj->startDate = $arg_array['startDate'];
            $coupon_obj->endDate = $arg_array['endDate'];
            $coupon_obj->couponType = $arg_array['couponType'];
            $coupon_obj->amount = $arg_array['amount'];
            $coupon_obj->limitMoney = $arg_array['limitMoney'];
            $coupon_obj->wncode = $arg_array['wncode'];
            $coupon_obj->totalNum = $arg_array['totalNum'];
            $coupon_obj->validity = $arg_array['validity'];
            $coupon_obj->useNum = 0;
            $coupon_obj->goodsSelectorID = $arg_array['goodsSelectorID'];
            $coupon_obj->userSelectorID = $arg_array['userSelectorID'];
            $coupon_obj->description = $commHandler->convertVar($arg_array['description']);

            $coupon_obj->useType = $arg_array['useType'];
            $coupon_obj->code_number = $arg_array['code_number'];
            $coupon_obj->departmentID = $arg_array['departmentID'];
            $coupon_obj->departmentName = $arg_array['departmentName'];
            $this->dbca->save($coupon_obj);

            if ($arg_array['couponID'] > 0) {
                return array( 'code' => 200, 'message' => '优惠券修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '优惠券新增成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 生成优惠券编号
     * @return string
     */
    public function getCode() {
        return 'EB' . strtoupper(uniqid()) . rand ( 100, 999 );
    }


    /**
     * 发放优惠券
     * @param int $couponID 优惠券ID
     * @param array $c_array 会员名数组
     * $c_array = array( '会员名', '会员名', '会员名', '会员名' )
     * @return array
     */
    public function createCouponCode( $couponID, $c_array = array() ) {

        if (!isset($couponID) || !is_numeric($couponID)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        $datetime = date(G_DEFAULT_DATETIME_FORMAT);

        try {

            $this->dbca->beginTransaction();

            //查询优惠券信息并修改或新增优惠券
            $coupon_obj = new entity('promotion_coupon');

            $coupon_obj->couponID = $couponID;
            if (!$this->dbca->fetch($coupon_obj)) {
                throw new Exception('优惠券信息没有找到', 404);
            }
            if ($coupon_obj->couponType == 3) {
                throw new Exception('万能码优惠券不能生成编号', 404);
            }

            if ($coupon_obj->couponType == 1) { //编号礼品券生产

                if ($coupon_obj->isGenerate == 1) {
                    throw new Exception('优惠券编号已生成', 404);
                }

                //一次生产的优惠券数量
                $num = 5000;

                //循环生生产次数
                $times = ceil( $coupon_obj->totalNum / $num );
				if ($times == 0) {
                    $times = 1;
                }
                
                //生产优惠券
                $i = 0;

                $already_product_num = 0;
                
                while($i < $times) {



                    //最后一次循环
                    if($i == $times -1 ){
                        $num = $coupon_obj->totalNum - $already_product_num;
                    }

                    $sql = 'INSERT INTO promotion_coupon_code(uuid,timeStamp,creator,createTime,code,couponID,amount,couponType,limitMoney,endDate) VALUES ';

                    for($j = 0; $j < $num; $j++) {

                        $code = $this->getCode();

                        if ($j == $num - 1) {
                            $sql .= sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,"%s")',
                                            make_uuid(), $datetime, 'system__publish',
                                            $datetime, $code, $coupon_obj->couponID, $coupon_obj->amount,
                                            $coupon_obj->couponType, $coupon_obj->limitMoney, $coupon_obj->endDate);
                        } else {
                            $sql .= sprintf('("%s","%s","%s","%s","%s",%s,%s,%s,%s,"%s"),',
                                            make_uuid(), $datetime, 'system__publish',
                                            $datetime, $code, $coupon_obj->couponID, $coupon_obj->amount,
                                            $coupon_obj->couponType, $coupon_obj->limitMoney, $coupon_obj->endDate);
                        }

                    }

                    if ($this->dbca->execute($sql)) {
                        ++$i;
                        $already_product_num += $num;
                    }

                }

                //更新优惠券信息
                $coupon_obj->isGenerate = 1;
                $this->dbca->save( $coupon_obj );

            } else { //账户礼品券生产

                if (empty($c_array)) {
                    throw new Exception('没有会员数据', 404);
                }

                $date = date(G_DEFAULT_DATE_FORMAT);

                foreach($c_array as &$custID) {

                    if (empty($custID)) {
                        continue;
                    }

                    //查询会员信息
                    $cust_obj = new entity('cust_master');
                    $cust_obj->custID = $custID;
                    if (!$this->dbca->fetch($cust_obj)) {
                        continue;
                    }

                    $i = 0;
                    while($i == 0) {
                        $code_obj = new entity('promotion_coupon_code');
                        $code_obj->code = $this->getCode();
                        if ($this->dbca->fetch($code_obj)) {
                            continue;
                        }
                        $code_obj->creator = 'system__publish';
                        $code_obj->couponID = $coupon_obj->couponID;
                        $code_obj->amount = $coupon_obj->amount;
                        $code_obj->couponType = $coupon_obj->couponType;
                        $code_obj->limitMoney = $coupon_obj->limitMoney;
                        $code_obj->pcustID = $cust_obj->pcustID;
                        $code_obj->endDate = date("Y-m-d", strtotime("$date   +$coupon_obj->validity   day"));
                        $this->dbca->save($code_obj);
                        $i++;
                    }

                }

            }

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '优惠券编号生成成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                echo json_encode( array('code' => 500 ,'message' => '系统错误') );
            }

        }

    }

    /**
     * 检查优惠券编号
     * @param string $code 优惠券编号
     * @param int $pcustID 会员号
     * @param array $goods_array 商品数组
     * @return array
     */
    public function checkCoupon( $code, $pcustID, $goods_array ) {

        if (!isset($code, $pcustID, $goods_array) || empty($code) || !is_numeric($pcustID) || empty($goods_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $this->dbca );

        //实例会员类
        $custSelector = new custSelector( $this->dbca );

        //查询优惠券编号信息
        $arg_array = array(
            'code' => $code
        );
        $coupon_code_array = $this->searchCouponCode( $arg_array );
        if (!$coupon_code_array) {

            //优惠券编号信息没有找到，检查是否是万能码
            $arg_array = array(
                'wncode' => $code,
                'couponType' => 3,
                'useFlg' => 1
            );
            $coupon_array = $this->searchCoupon( $arg_array );
            if (!$coupon_array) {
                return array( 'code' => 404, 'message' => '优惠券不存在' );
            }
            $coupon_array = $coupon_array[0];

            //检查优惠券是否已过期
            if ($coupon_array['endDate'] < date(G_DEFAULT_DATETIME_FORMAT)) {
                return array( 'code' => 404, 'message' => '优惠券已过期' );
            }

        } else {

            //检查是否是当前会员的优惠券
            if (!empty($coupon_code_array['pcustID']) && $coupon_code_array['pcustID'] != $pcustID) {
                return array( 'code' => 404, 'message' => '优惠券不存在' );
            }

            //检查优惠券是否已过期
            if ($coupon_code_array['endDate'] < date(G_DEFAULT_DATETIME_FORMAT)) {
                return array( 'code' => 404, 'message' => '优惠券已过期' );
            }

            //检查优惠券是否已使用
            if (!empty($coupon_code_array['billNo'])) {
                return array( 'code' => 404, 'message' => '优惠券已使用' );
            }

            //查询优惠券信息
            $arg_array = array(
                'couponID' => $coupon_code_array['couponID'],
                'useFlg' => 1
            );
            $coupon_array = $this->searchCoupon( $arg_array );
            if (!$coupon_array) {
                return array( 'code' => 404, 'message' => '优惠券不存在' );
            }
            $coupon_array = $coupon_array[0];

        }

        //检查会员是否符合条件
        if (!empty($coupon_array['userSelector']) && !$custSelector->isValid($coupon_array['userSelector'], $pcustID)) {
            return array( 'code' => 404, 'message' => '会员不符合使用条件' );
        }

        //符合条件商品总金额、总数量
        $total_money = 0;
        $goods_amount = 0;

        //筛选商品
        foreach ($goods_array as &$goods) {

            if (!empty($coupon_array['goodsSelector']) && !$gSelectorHandler->isValid($coupon_array['goodsSelector'], $goods['postID']))
                continue;

            $total_money += $goods['price'] * $goods['goodsAmount'];
            $goods_amount += $goods['goodsAmount'];

        }

        //没有符合条件的商品
        if ($goods_amount == 0) {
            return array( 'code' => 404, 'message' => '没有符合优惠券条件的商品' );
        }

        //商品金额不满足优惠券使用限额
        if ($total_money < $coupon_array['limitMoney']) {
            return array( 'code' => 404, 'message' => '商品金额不满足优惠券使用限额' );
        }

        //编号优惠券没有绑定会员
        if ($coupon_array['couponType'] == 1 && empty($coupon_code_array['pcustID'])) {
            $update_sql = 'UPDATE promotion_coupon_code SET pcustID = ? WHERE code = ?';
            $this->dbca->stmt_query($update_sql, 'is', $pcustID, $code);
        }

        $couponID = $coupon_array['couponID'];
        $amount = $coupon_array['amount'];

        $return_array = array(
            'code' => 200,
            'message' => 'ok',
            'data' => array(
                'code' => $code,
                'amount' => $amount,
                'couponID' => $couponID,
                'couponType' => $coupon_array['couponType']
            )
        );

        return $return_array;

    }

    /**
     * 回滚已使用的优惠券
     * @param string $coupon_code 优惠券编号
     * @param int $bill_no 订单号
     * @return array
     */
    public function rollbackCoupon( $coupon_code, $bill_no ) {

        if (!isset($coupon_code, $bill_no) || empty($coupon_code) || empty($bill_no)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        $code_obj = new entity('promotion_coupon_code');
        $code_obj->code = $coupon_code;
        $code_obj->billNo = $bill_no;
        if (!$this->dbca->fetch($code_obj)) {
            return array( 'code' => 404, 'message' => '优惠券没有找到' );
        }
        $code_obj->billNo = null;
        $code_obj->useTime = null;
        $code_obj->useAmount = null;
        $this->dbca->save( $code_obj );

        return array( 'code' => 200, 'message' => 'ok' );

    }

}
